package com.llg.service;

import com.llg.model.BoxSizeVO;
import com.llg.model.BoxVO;
import com.llg.model.code.CommonCode;
import com.llg.model.response.DataResult;
import com.llg.model.response.PageResult;
import com.llg.model.response.ResponseResult;
import com.llg.pojo.BoxPO;
import com.llg.pojo.BoxSizePO;
import com.llg.repository.BoxPORepository;
import com.llg.repository.BoxSizePORepository;
import com.llg.util.ConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BoxSizeService {

    private final BoxPORepository boxPORepository;
    private final BoxSizePORepository boxSizePORepository;

    @Autowired
    public BoxSizeService(BoxPORepository boxPORepository, BoxSizePORepository boxSizePORepository) {
        this.boxPORepository = boxPORepository;
        this.boxSizePORepository = boxSizePORepository;
    }

    public PageResult<BoxSizeVO> findAll() {
        List<BoxSizePO> poList = boxSizePORepository.findAll();
        List<BoxSizeVO> voList = ConvertUtils.povoListConvert(poList, BoxSizeVO.class);
        return new PageResult<>(CommonCode.SUCCESS, voList.size(), 1, voList);
    }


    public DataResult<BoxSizeVO> add(BoxSizeVO boxVO) {
        BoxSizePO po = ConvertUtils.povoConvert(boxVO, BoxSizePO.class);
        BoxSizePO save = boxSizePORepository.save(po);
        return new DataResult<>(CommonCode.SUCCESS, ConvertUtils.povoConvert(save, BoxSizeVO.class));
    }

    public ResponseResult delete(int id) {
        boxSizePORepository.deleteById(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public ResponseResult update(BoxSizeVO boxVO) {
        Optional<BoxSizePO> optional = boxSizePORepository.findById(boxVO.getId());
        if (optional.isPresent()) {
            BoxSizePO po = optional.get();
            BeanUtils.copyProperties(boxVO, po);
            BoxSizePO save = boxSizePORepository.save(po);
            return new DataResult<>(CommonCode.SUCCESS, ConvertUtils.povoConvert(save, BoxSizeVO.class));
        }
        return new ResponseResult(CommonCode.NO_EXIST_ID);
    }

    public DataResult<BoxSizeVO> findOne(int id) {
        Optional<BoxSizePO> optional = boxSizePORepository.findById(id);
        if (optional.isPresent()) {
            BoxSizePO po = optional.get();
            BoxSizeVO boxPO = ConvertUtils.povoConvert(po, BoxSizeVO.class);
            return new DataResult<>(CommonCode.SUCCESS, boxPO);
        }

        return new DataResult<>(CommonCode.NO_EXIST_ID, null);
    }
}
